package com.xca.bindingwork.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.xca.bindingwork.databinding.ItemBinding;
import com.xca.bindingwork.entity.PetEntity;
import com.xca.bindingwork.view.IntroduceActivity;

import java.io.Serializable;
import java.util.List;

public class PetsAdapter extends RecyclerView.Adapter<PetsAdapter.ViewHolder>{
    private List<PetEntity.ResultBean.ListBean> pets ;
    private Context context ;
    private Activity activity ;
    public PetsAdapter(List<PetEntity.ResultBean.ListBean> pets, Context context, Activity activity){
        this.pets = pets;
        this.context = context;
        this.activity = activity;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        ItemBinding binding = ItemBinding.inflate(inflater,parent,false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        PetEntity.ResultBean.ListBean pet = pets.get(position);
        holder.binding.setListInfo(pet);
        Glide.with(activity).load(pet.getCoverURL()).into(holder.binding.itemImg);
        holder.binding.executePendingBindings(); // 刷新
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转
                Intent intent = new Intent(context, IntroduceActivity.class);
                Gson gson = new Gson() ;
                intent.putExtra("pet" , gson.toJson(pet)) ;
                activity.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return pets == null ? 0 : pets.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ItemBinding binding;
        public ViewHolder(ItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}
